import {
    deleteFilmTelevisionUsingPOST,
    getFilmTelevisionByIdUsingPOST,
    updateFilmTelevisionUsingPOST,
} from '@/services/otherworldly-station-backend/FilmTelevisionController';
import { MinusOutlined, PlusOutlined } from '@ant-design/icons';
import { ProCard } from '@ant-design/pro-components';
import {
    Badge,
    Button,
    Card,
    Divider,
    Image,
    InputNumber,
    List,
    message,
    Modal,
    Popconfirm,
    Select,
    Spin,
    Tag,
} from 'antd';
import React, { CSSProperties, useState } from 'react';
import styles from './index.less';

export type Props = {
    records: API.FilmTelevisionVO[];
    recordsCount: number;
    setCurrentPage: (page: number) => void;
    currentPage: number;
    searchKey: string;
    onSearchData: (limit: number, offset: number, value: string) => Promise<void>;
};
const iconStyles: CSSProperties = {
    color: 'rgba(0, 0, 0, 0.2)',
    fontSize: '18px',
    verticalAlign: 'middle',
    cursor: 'pointer',
};

const getImages = (_url: string | undefined) => {
    if (_url !== undefined) {
        let _u = _url.substring(7);
        return 'https://images.weserv.nl/?url=' + _u;
    }
};
const CardList: React.FC<Props> = (props) => {
    const { records, recordsCount, currentPage, setCurrentPage, onSearchData, searchKey } = props;
    const [modalOpen, setModalOpen] = useState(false);
    const [airWeekDateModalOpen, setAirWeekDateModalOpen] = useState(false);
    const [submitLoading, setSubmitLoading] = useState(false);
    const [movieItem, setMovieItem] = useState<API.FilmTelevisionVO>({});
    const [isCompleteLoading, setIsCompleteLoading] = useState<boolean>(false);
    const [airWeekDate, setAirWeekDate] = useState<string>('');
    const [watchProgress, setWatchProgress] = useState<number>(0);

    const deleteMyFavorite = (id: number) => {
        // 取消收藏
        setSubmitLoading(true);
        // 取消收藏，删除本地记录
        deleteFilmTelevisionUsingPOST({ id })
            .then(async (res) => {
                if (res.code === 0) {
                    message.warning('影片已从您的影视列表中移除');
                    await onSearchData(20, 0, '');
                }
            })
            .finally(() => {
                setModalOpen(false);
                setSubmitLoading(false);
            });
    };

    /**
     * 根据ID获取影片详情
     * @param id
     */
    const showFilmDetail = (id: number) => {
        setIsCompleteLoading(true);
        setMovieItem({});
        // 获取影片详情
        getFilmTelevisionByIdUsingPOST({ id }).then((res) => {
            if (res.code === 0) {
                let data = res.data as API.FilmTelevisionVO;
                console.log('data:', data);
                setWatchProgress(data.watchProgress as number);
                setMovieItem(data);
                setAirWeekDate(data.airWeekDate as string);
                setIsCompleteLoading(false);
                setModalOpen(true);
            }
        });
    };

    /**
     * 根据ID修改观影进度
     * @param value
     */
    const updateWatchProgress = (value: any) => {
        setWatchProgress(value);
        if (value && value > 0) {
            const body = { ...movieItem, watchProgress: value };
            updateFilmTelevisionUsingPOST(body).then((res) => {
                if (res.code !== 0) {
                    message.error(res.message);
                }
            });
        }
    };

    /**
     * 根据ID修改更新时间
     * @param value
     */
    const updateFilmAirDate = (value: any) => {
        if (value) {
            const body = { ...movieItem, airWeekDate: value };
            updateFilmTelevisionUsingPOST(body).then((res) => {
                if (res.code === 0) {
                    setAirWeekDateModalOpen(false);
                } else {
                    message.error(res.message);
                }
            });
        }
    };

    /**
     * 根据ID修改观影状态
     * @param value
     */
    const updateFilmWatchStatus = (value: any) => {
        setSubmitLoading(true);
        const body = { ...movieItem, watchStatus: value };
        updateFilmTelevisionUsingPOST(body).then(async (res) => {
            if (res.code !== 0) {
                message.error(res.message);
            } else if (res.code === 0) {
                await onSearchData(20, currentPage, searchKey);
                setModalOpen(false);
                setSubmitLoading(false);
            }
        });
    };

    /**
     * 根据tabKey判断按钮显示
     */
    const getFooterButton = () => {
        if (movieItem.watchStatus === 1) {
            // 想看
            return [
                <Popconfirm
                    key="deleteFilm"
                    title="删除影片"
                    description="你确定删除该影片吗?"
                    onConfirm={() => {
                        deleteMyFavorite(movieItem.id as number);
                    }}
                    okText="确定"
                >
                    <Button key={'deleteFilm'}>删除</Button>
                </Popconfirm>,
                <Button key={'doing'} type="default" onClick={() => updateFilmWatchStatus(2)}>
                    正在看
                </Button>,
                <Button key={'collect'} type="primary" onClick={() => updateFilmWatchStatus(3)}>
                    已看完
                </Button>,
            ];
        } else if (movieItem.watchStatus === 2) {
            // 在看
            return [
                <Popconfirm
                    key="deleteFilm"
                    title="删除影片"
                    description="你确定删除该影片吗?"
                    onConfirm={() => {
                        deleteMyFavorite(movieItem.id as number);
                    }}
                    okText="确定"
                >
                    <Button key={'deleteFilm'}>删除</Button>
                </Popconfirm>,
                <Button key={'wish'} type="default" onClick={() => updateFilmWatchStatus(1)}>
                    想看
                </Button>,
                <Button key={'collect'} type="primary" onClick={() => updateFilmWatchStatus(3)}>
                    已看完
                </Button>,
            ];
        } else if (movieItem.watchStatus === 3) {
            // 已看完
            return [
                <Popconfirm
                    key="deleteFilm"
                    title="删除影片"
                    description="你确定删除该影片吗?"
                    onConfirm={() => {
                        deleteMyFavorite(movieItem.id as number);
                    }}
                    okText="确定"
                >
                    <Button key={'deleteFilm'}>删除</Button>
                </Popconfirm>,
                <Button key={'collect'} type="default" onClick={() => updateFilmWatchStatus(1)}>
                    想看
                </Button>,
                <Button key={'doing'} type="primary" onClick={() => updateFilmWatchStatus(2)}>
                    还在看
                </Button>,
            ];
        }
    };

    /**
     * 渲染标签
     */
    const renderTags = () => {
        return movieItem.tags?.slice(0, 6).map((item, index) => (
            <Tag key={item} bordered={true} color="#fa5822" style={{ marginBottom: '10px' }}>
                {item}
            </Tag>
        ));
    };

    /**
     * 渲染观看进度
     */
    const renderWatchProgressSection = () => {
        if (movieItem.watchStatus === 2 && movieItem.type === '剧集') {
            return (
                <ProCard>
                    观看集数：
                    <Button
                        type="primary"
                        icon={<MinusOutlined />}
                        size={'small'}
                        onClick={() => updateWatchProgress(watchProgress - 1)}
                    />
                    <InputNumber
                        size={'middle'}
                        min={0}
                        value={watchProgress}
                        onChange={(value) => updateWatchProgress(value)}
                        style={{ width: '70px', margin: '0 8px' }}
                    />
                    <Button
                        type="primary"
                        icon={<PlusOutlined />}
                        size={'small'}
                        onClick={() => updateWatchProgress(watchProgress + 1)}
                    />
                </ProCard>
            );
        }
        return null;
    };

    return (
        records && (
            <>
                <Spin size="large" spinning={submitLoading}>
                    <Modal
                        width="500px"
                        centered
                        open={modalOpen}
                        okText={'删除'}
                        onCancel={() => setModalOpen(false)}
                        footer={getFooterButton()}
                    >
                        <ProCard
                            direction="column"
                            ghost
                            gutter={{ xs: 1, sm: 1, md: 1, lg: 1, xl: 1, xxl: 2 }}
                            style={{ overflow: 'auto', marginTop: '15px' }}
                            className={styles.coverCardList}
                        >
                            <ProCard style={{ textAlign: 'center' }}>
                                <Image
                                    width={200}
                                    src={
                                        !movieItem.images?.grid
                                            ? getImages(movieItem.images?.large)
                                            : movieItem.images?.large
                                    }
                                />
                            </ProCard>
                            <ProCard>
                                <h2>
                                    <b>{movieItem.name}</b>
                                    <span></span>
                                    <span
                                        style={{
                                            marginLeft: '10px',
                                            fontSize: '18px',
                                        }}
                                    >
                                        {movieItem.score ? movieItem.score : 0} 分
                                    </span>
                                </h2>
                                {renderTags()}
                                <Divider style={{ margin: '0 0 10px 0' }} />
                                <div style={{ height: 'auto' }}>{movieItem.description}</div>
                            </ProCard>
                            {renderWatchProgressSection()}
                            <ProCard>
                                更新时间：{movieItem.airWeekDate ? movieItem.airWeekDate : '无 '}
                                <Button
                                    style={{ marginLeft: '12px' }}
                                    type="primary"
                                    size="small"
                                    onClick={() => {
                                        setAirWeekDateModalOpen(true);
                                    }}
                                >
                                    修改更新时间
                                </Button>
                            </ProCard>
                        </ProCard>
                    </Modal>
                </Spin>

                <Modal
                    width="300px"
                    centered
                    open={airWeekDateModalOpen}
                    onOk={() => updateFilmAirDate(airWeekDate)}
                    onCancel={() => setAirWeekDateModalOpen(false)}
                >
                    <ProCard>
                        更新时间：
                        <Select
                            value={airWeekDate}
                            style={{ width: 120 }}
                            onChange={(value) => {
                                setAirWeekDate(value);
                            }}
                            options={[
                                { value: '星期一', label: '星期一' },
                                { value: '星期二', label: '星期二' },
                                { value: '星期三', label: '星期三' },
                                { value: '星期四', label: '星期四' },
                                { value: '星期五', label: '星期五' },
                                { value: '星期六', label: '星期六' },
                                { value: '星期日', label: '星期日' },
                            ]}
                        />
                    </ProCard>
                </Modal>
                <Spin size="large" spinning={isCompleteLoading}>
                    <List<any>
                        className={styles.coverCardList}
                        rowKey="id"
                        grid={{ gutter: 24, xxl: 8, xl: 6, lg: 4, md: 4, sm: 2, xs: 1 }}
                        dataSource={records}
                        renderItem={(item) => {
                            return (
                                <List.Item>
                                    <Badge.Ribbon text={item.type}>
                                        <Card
                                            className={styles.card}
                                            hoverable
                                            cover={
                                                <img
                                                    alt={item.images?.medium}
                                                    src={getImages(item.images.medium)}
                                                />
                                            }
                                            onClick={() => {
                                                showFilmDetail(item.id);
                                            }}
                                        >
                                            <Card.Meta
                                                title={<a>{item.name}</a>}
                                                description={item.airWeekday}
                                            />
                                            <div className={styles.cardItemContent}>
                                                <span>
                                                    {item.airWeekDate ? item.airWeekDate : null}
                                                </span>
                                                <div
                                                    style={{
                                                        color: 'rgba(0, 0, 0, 0.6)',
                                                    }}
                                                >
                                                    {
                                                        <Tag
                                                            key={item}
                                                            bordered={true}
                                                            color="#fa5822"
                                                            style={{ marginBottom: '10px' }}
                                                        >
                                                            {(() => {
                                                                const {
                                                                    watchStatus,
                                                                    watchProgress,
                                                                } = item;

                                                                if (watchStatus === 1) {
                                                                    return '想看';
                                                                } else if (watchStatus === 2) {
                                                                    return watchProgress
                                                                        ? `第${watchProgress}集`
                                                                        : '第1集';
                                                                } else if (watchStatus === 3) {
                                                                    return '看过';
                                                                } else {
                                                                    return null;
                                                                }
                                                            })()}
                                                        </Tag>
                                                    }
                                                </div>
                                            </div>
                                        </Card>
                                    </Badge.Ribbon>
                                </List.Item>
                            );
                        }}
                    />
                    {/*{recordsCount > 20 ? (
                        <Pagination
                            style={{textAlign: 'center'}}
                            simple
                            defaultCurrent={currentPage}
                            defaultPageSize={20}
                            total={recordsCount}
                            onChange={async (page, pageSize) => {
                                console.log(page, pageSize)
                                await onSearchData(pageSize, page, searchKey);
                                setCurrentPage(page);
                                window.scrollTo({
                                    top: 0,
                                    behavior: 'smooth',
                                });
                            }}
                        />
                    ) : null}*/}
                </Spin>
            </>
        )
    );
};

// @ts-ignore
export default CardList;
